import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        initFlowRules();
        while (true) {
            doSomething();
        }

    }

    //定义资源
    private static void doSomething(){
        try(Entry entry = SphU.entry("doSomething")) {
            //业务逻辑处理
            System.out.println("Hello world:"+System.currentTimeMillis());
        }catch (BlockException ex) {

        }
    }

    //对保护的资源定义限流规则
    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<FlowRule>();
        FlowRule rule = new FlowRule();
        rule.setResource("doSomething");
        //限流阈值类型，QPS模式（1）或并发线程数模式（0）
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //限流阈值
        rule.setCount(20);
        //是否针对调用来源进行限流，默认是default,即不区分调用来源
        rule.setLimitApp("default");
        //调用关系限流策略：直接、链路、关联
        rule.setStrategy(RuleConstant.STRATEGY_CHAIN);
        //流控行为，包括直接拒绝、排队等待，慢启动模式,默认是直接拒绝
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        //是否是集群限流，默认为否
        rule.setClusterMode(false);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }
}
